use log::info;
use tokio::net::TcpStream;
use tokio::io::AsyncReadExt;

use crate::{cli::Cli, error::Error};

pub async fn list(mut stream: TcpStream, cli: &Cli) -> Result<(), Error> {
    let command = format!("{}\n",
        cli.command
    );
    match stream.try_write(command.as_bytes()) {
        Ok(_) => {
            info!("command: {command}");
        }
        Err(e) => {
            return Err(e.into());
        }
    }

    let mut buffer = [0; 1024 * 100];
    match stream.read(&mut buffer).await {
        Ok(n) if n > 0 => {
            println!("{}", String::from_utf8_lossy(&buffer[..n]).to_string());
        },
        Ok(_) => {},
        Err(e) => return Err(Error::CustomError("command list read message error".to_owned())),
    };

    Ok(())
}